<template>
  <!-- 组件列表 -->
  <div class="create-component-list">
    <div
      v-for="(item, index) in props.list"
      :key="index"
      class="component-item"
      @click="onItemClick(item)"
    >
      <l-text v-bind="item"></l-text>
    </div>
  </div>
  <StyledUploader @success="onImageUploaded"></StyledUploader>
</template>

<script lang="ts" setup>
import { defineEmits, defineProps } from 'vue';
import { v4 as uuidv4 } from 'uuid';
import { message } from 'ant-design-vue';
import StyledUploader from '../components/StyledUploader.vue';
import LText from '../components/LText.vue';
import { RespUploadData } from '../store/respTypes';
import { ComponentData } from '../store/editor';
import { getImageDimensions } from '../helper';
import { imageDefaultProps } from '../defaultProps';
const props: any = defineProps({
  list: {
    type: Array,
    required: true
  }
});

const emit = defineEmits(['on-item-click']);
const onItemClick = (props: any) => {
  console.log(props);

  const componentData: any = {
    name: 'l-text',
    id: uuidv4(),
    props
  };
  emit('on-item-click', componentData);
};

const onImageUploaded = (data: { resp: RespUploadData; file: File }) => {
  console.log(data, 'onImageUploaded');
  const { resp, file } = data;
  const componentData: ComponentData = {
    name: 'l-image',
    id: uuidv4(),
    props: {
      ...imageDefaultProps
    }
  };
  message.success('上传成功');
  componentData.props.src = resp.data.urls[0];
  getImageDimensions(file).then(({ width }) => {
    const maxWidth = 373;
    componentData.props.width = (width > maxWidth ? maxWidth : width) + 'px';
    emit('on-item-click', componentData);
  });
};
</script>

<style scoped>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}
.component-item > * {
  position: static !important;
}
</style>
